import React, { Component } from 'react'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout'
import { BasicPagination, compareNum, compareString, compareDate, TableCustomize, openSuccessModal, openModalMessage } from '../../../components/TableCustomize'
import { Button, Alert, Divider, Modal } from 'antd'
import { Redirect } from 'react-router-dom'
import TopForm from './TopForm'
import AddForm from './AddForm'
import img from '../../../assets/img/flame.png'
import * as OweMaterial from '../../../axios/OweMaterial'
import * as StayGrantService from '../../../axios/StayGrant'
import { getDate } from '../../../utils/action'
import { withPermission } from '../../../components/withpermission'
const RefreshButton = withPermission(Button, 'sync')
const CHFButton = withPermission(Button, 'cuihuifu')
const BJButton = withPermission(Button, 'bianjijiaoqi')
const TJButton = withPermission(Button, 'tijiaoqianliao')
const PrintButton = withPermission(Button, 'printer')
export default class OweSupplies extends Component {
    state = {
        columns: [
            {
                title: '欠料单号',
                dataIndex: 'materialShortageCode',
                sorter: (a, b) => compareString(a.materialShortageCode, b.materialShortageCode),
                width: 150,
            },
            {
                title: '批号',
                dataIndex: 'batchNo',
                sorter: (a, b) => compareString(a.batchNo, b.batchNo),
                width: 100,
            },
            {
                title: '装配部门',
                dataIndex: 'departmentId',
                sorter: (a, b) => compareString(a.departmentId, b.departmentId),
                width: 100,
            },
            {
                title: '机型',
                dataIndex: 'model',
                sorter: (a, b) => compareString(a.model, b.model),
                width: 100,
            },
            {
                title: '欠料项',
                dataIndex: 'total',
                sorter: (a, b) => compareNum(a.total, b.total),
                width: 80,
            },
            {
                title: '第一交机时间',
                dataIndex: 'firstDeliveryTime',
                width: 150,
                sorter: (a, b) => compareDate(a.firstDeliveryTime, b.firstDeliveryTime),
            },
            { dataIndex: '' }
            // {
            //     title: '操作',
            //     dataIndex: 'opes',
            //     key: 'opes',
            //     ellipsis: true,
            //     render: (text, record, index) =>
            //         <div>
            //             {/* <a onClick={this.redactHandOverDate.bind(null, record)}>{'编辑交期'}</a> */}
            //             {/* <Divider type="vertical" /> */}
            //             <a onClick={this.urgeReply.bind(null, record)}>{'催回复'}</a>
            //             <Divider type="vertical" />
            //             <a onClick={this.cancel.bind(null, record, index)}>{'取消'}</a>
            //         </div>
            // },
        ],
        dataSource: [
        ],
        columnsInterior: [
            {
                title: '序号',
                dataIndex: 'serialNumber',
                render: (text, record, index) =>
                    <div style={{ display: 'flex' }}>
                        <div>{index + 1}</div>
                        {record.anxious ? <img src={img} style={{ width: '18px', height: '18px' }} /> : null}
                    </div>,
                width: 60,
            },
            {
                title: '物料编码',
                dataIndex: 'partCode',
                sorter: (a, b) => compareNum(a.partCode, b.partCode),
                width: 100,
            },
            {
                title: '图号',
                dataIndex: 'paperCode',
                sorter: (a, b) => compareNum(a.paperCode, b.paperCode),
                width: 180,
            },
            {
                title: '部件',
                dataIndex: 'component',
                width: 80,
            },
            {
                title: '物料名称',
                dataIndex: 'partName',
                width: 100,
            },
            {
                title: '物料规格',
                dataIndex: 'partSpec',
                width: 100,
            },
            {
                title: '单位',
                dataIndex: 'partUnit',
                width: 80,
            },
            {
                title: '欠料/需求量',
                dataIndex: 'needNum',
                sorter: (a, b) => compareNum(a.needNum, b.needNum),
                width: 120,
            },
            {
                title: '仓库',
                dataIndex: 'storeName',
                sorter: (a, b) => compareNum(a.storeName, b.storeName),
                width: 100,
            },
            {
                title: '领料单号',
                dataIndex: 'acceptCode',
                sorter: (a, b) => compareNum(a.acceptCode, b.acceptCode),
                width: 150,
            },
            {
                title: '欠料创建时间',
                dataIndex: 'createTime',
                sorter: (a, b) => compareNum(a.createTime, b.createTime),
                width: 150,
            },
            {
                title: '创建人',
                dataIndex: 'creator',
                sorter: (a, b) => compareNum(a.creator, b.creator),
                width: 100,
            },
            {
                title: '交期回复',
                dataIndex: 'deliveryReply',
                sorter: (a, b) => compareNum(a.deliveryReply, b.deliveryReply),
                editable: true,
                width: 150,
            },
            {
                title: '操作',
                dataIndex: 'opes',
                width: 180,
                render: (text, record, index) =>
                    <div>
                        <a onClick={this.redactHandOverDateInterior.bind(null, record)}>{'编辑交期'}</a>
                        <Divider type="vertical" />
                        <a onClick={this.urgeReplyInterior.bind(null, record)}>{'催回复'}</a>
                        <Divider type="vertical" />
                        <a onClick={this.cancelInterior.bind(null, record, index)}>{'取消'}</a>
                    </div>
            },
            { dataIndex: '' }
        ],
        dataSourceInterior: [
        ],
        advanced: false,
        visible: false,
        formData: {},
        loginFlag: false,
        some: null,
        selectedRowKeys: [],
        selectedRows: [],
        selectedRowKeys1: [],
        selectedRows1: [],
        row: [],
        row1: [],
        values: {},
        paging: {},
        lineId: [],
        allCompileDate: false
    }
    UNSAFE_componentWillMount() {
        this.fetch()
        this.getWorkShopList()
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    //初始化加载数据
    fetch = (page = 1, size = 100) => {
        const { values } = this.state
        this.setState({
            loading: true,
            one: false,
            drawerVisible: false,
            formData: {},
            values: {},
            // 操作后清除选中
            selectedRowKeys: [],
            selectedRows: [],
            selectedRowKeys1: [],
            selectedRows1: [],
            some: null,
            paging: { pageNum: page, pageSize: size }
        })
        let a = { pageNum: page, pageSize: size }
        setTimeout(() => {
            this.search({ ...values, ...a })
        }, 300);
    }
    // 查询接口
    search = (value, paging) => {
        let userId = localStorage.getItem('userId')
        OweMaterial.materialShortageMange({ ...value, ...paging, userId: userId }).then((item) => {
            console.log('查询数据', item);
            if (item.data.code === 200) {
                this.setState({
                    loading: false,
                    dataSource: item.data.data,
                    // 操作后清除选中
                    selectedRowKeys: [],
                    selectedRows: [],
                    some: null,
                    paging: {
                        pageNum: item.data.pageNum,
                        pageSize: item.data.pageSize,
                        total: item.data.total,
                    }
                })
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 查询接口
    particulars = (value) => {
        let userId = localStorage.getItem('userId')
        console.log({ ...value, userId: userId });
        OweMaterial.materialShortageMangeDetail({ ...value, userId: userId }).then((item) => {
            console.log('查询数据', item);
            if (item.data.code === 200) {
                this.setState({
                    dataSourceInterior: item.data.data,
                })
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    getWorkShopList = () => {
        StayGrantService.workShopList().then(res => {
            if (res.data.code !== 200) {
                openModalMessage('warning', res.data.msg);
                return;
            }
            const workShopList = res.data && res.data.data ? res.data.data : []
            this.setState({ workShopList })
        }).catch(err => {
            openModalMessage('error', err.message);
        })
    }
    //编辑交期确认按钮
    submitMenu = () => {
        const { lineId, allCompileDate, selectedRows, row } = this.state
        const then = this
        this.setState({
            confirmLoading: true
        })
        this.formAdd.validateFields((err, value) => {
            if (err) return;
            let data2 = [
                {
                    deliveryReply: value.redactDate,
                    id: lineId,
                    userId: Number(localStorage.getItem('userId')),
                }
            ]
            let data1 = []
            selectedRows.forEach((value_1, index_1) => {
                data1.push({
                    deliveryReply: value.redactDate,
                    id: value_1.id,
                    userId: Number(localStorage.getItem('userId')),
                })
            })
            console.log(allCompileDate ? data1 : data2);
            OweMaterial.editDeliveryDate(allCompileDate ? data1 : data2).then((value) => {
                if (value.data.code !== 200) {
                    this.setState({
                        confirmLoading: false
                    })
                    openModalMessage('error', value.data.msg)
                    return
                }
                then.particulars({ id: row[0] })
                then.handleCancel()
            })
        })
    }
    // 高级查询
    advancedss = () => {
        console.log('高级查询');
        this.setState({ advanced: !this.state.advanced })
    }
    // 打印
    print = () => {
        console.log('打印');
    }
    // 提交欠料 (跳转至待发放物料)
    putIn = () => {
        this.setState({
            loginFlag: true
        })
    }
    // 编辑交期
    redact = () => {
        const { selectedRows } = this.state
        console.log('编辑交期');
        if (!selectedRows || !selectedRows.length) {
            openModalMessage('warning', '请选择内容')
            return
        }
        this.setState({
            visible: true,
            allCompileDate: true
        });
    }
    // 催回复
    urge = () => {
        const { selectedRows } = this.state
        if (!selectedRows || !selectedRows.length) {
            openModalMessage('warning', '请选择数据');
            return
        }
        let arr = '';
        selectedRows.forEach((value, index) => {
            arr += `&idList=${value.id}`
        })
        OweMaterial.promptReply(arr).then((value) => {
            if (value.data.code !== 200) {
                openModalMessage('warning', value.data.msg);
                return
            }
            openSuccessModal(value.data.msg)
        })
    }
    // 刷新
    refresh = () => {
        console.log('刷新');
        this.fetch();
    }
    handleSearch = value => {
        const { paging } = this.state
        // console.log('这是', value)
        let deliveryDate = null
        value.deliveryDate !== null && value.deliveryDate !== undefined ?
            deliveryDate = getDate(value.deliveryDate._d) : deliveryDate = null
        this.search({ ...value, deliveryDate: deliveryDate }, paging)
        this.setState({ values: value });
    };
    loadData = (value, dataSource) => {
        const { row } = this.state
        let data = [
            {
                deliveryReply: value.deliveryReply,
                id: value.id,
                userId: Number(localStorage.getItem('userId')),
            }
        ]
        OweMaterial.editDeliveryDate(data).then((value) => {
            if (value.data.code !== 200) {
                openModalMessage('error', value.data.msg)
                return
            }
            this.particulars({ id: row[0] })
        })
    }
    // 编辑交期（内）
    redactHandOverDateInterior = (record) => {
        console.log('编辑交期（内）', record);
        this.setState({
            visible: true,
            lineId: record.id
        })

    }
    // 催回复（内）
    urgeReplyInterior = (record) => {
        let arr = `idList=${record.id}`;
        OweMaterial.promptReply(arr).then((value) => {
            if (value.data.code !== 200) {
                openModalMessage('error', value.data.msg)
                return
            }
            openSuccessModal(value.data.msg)
        })
    }
    // 取消（内）
    cancelInterior = (record, index) => {
        const { row } = this.state
        let arr = `idList=${record.id}`;
        console.log(row);
        const then = this
        Modal.confirm({
            title: '确定删除吗？',
            onOk() {
                OweMaterial.cancelShortage(arr).then((value) => {
                    console.log('删除', value);
                    then.particulars({ id: row[0] })
                })
            },
            onCancel() { },
        })
    }
    handleCancel = e => {
        this.formAdd && this.formAdd.resetFields();
        this.setState({
            visible: false,
            confirmLoading: false,
            allCompileDate: false
        }, () => { this.fetch(); this.state.row.length > 0 && this.onExpand(true, { id: this.state.row[0] }) });

    };
    // 重置
    cz = () => {
        this.setState({
            values: {}
        }, () => { this.fetch() })
    }
    // 展开设置
    onExpand = (expanded, record) => {
        // const { row } = this.state
        // let id = row.length > 0 ? row[0] : null
        // if (id == record.id) {
        //     expanded = false
        // }
        if (expanded) {
            let userId = localStorage.getItem('userId')
            OweMaterial.materialShortageMangeDetail({ id: record.id, userId: userId }).then(res => {
                // console.log('展开', res);
                this.setState({
                    dataSourceInterior: res && res.data ? res.data.data : [],
                    row: [record.id],
                })
            })
            return
        }
        this.setState({
            row: [],
        })
    }
    render() {
        const { workShopList, paging, confirmLoading, selectedRows, visible, columns, some, loading, dataSource, advanced, formData, selectedRowKeys, selectedRowKeys1 } = this.state
        const batchNoStr1 = []
        selectedRows.forEach((value) => { batchNoStr1.push(value.batchNo) })
        const batchNoStr11 = Array.from(new Set(batchNoStr1))
        const batchNoStr = batchNoStr11.map(item => item).join(',')
        const rowSelection = {
            columnWidth: '60px',
            type: 'checkbox',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                let some = [...selectedRows].length
                this.setState({
                    some: some,
                    selectedRowKeys: selectedRowKeys,
                    selectedRows: selectedRows
                })
            },
        }
        const expandedRowRender = () => {
            const { columnsInterior, dataSourceInterior } = this.state
            const rowSelection = {
                columnWidth: '60px',
                type: 'checkbox',
                selectedRowKeys: selectedRowKeys1,
                onChange: (selectedRowKeys1, selectedRows1) => {
                    console.log(`内部table-selectedRowKeys: ${selectedRowKeys1}`, 'selectedRows: ', selectedRows1);
                    this.setState({
                        selectedRowKeys1: selectedRowKeys1,
                        selectedRows1: selectedRows1
                    })
                },
            }
            return <TableCustomize
                rowSelection={rowSelection}
                columns={columnsInterior}
                rowKey={(record) => record.id}
                dataSource={dataSourceInterior}
                pagination={false}
                allowDrafting={true}
                allowEditable={this.loadData}
                scroll={{ y: 300 }}
                expandedRowKeys={this.state.row1}
                rowClassName={(record, index) => {
                    return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                }}
            // onRow={(record, index) => ({
            //     onClick: this.pitch1.bind(this, record, index)
            // })}
            ></TableCustomize>;
        }
        // 跳转
        if (this.state.loginFlag) {
            return <Redirect to={{ pathname: "/stayGrant" }} />;
        }
        return (
            <div>
                <BasicLayoutSearch>
                    <TopForm onSearch={this.handleSearch}
                        onClick4={this.cz}
                        onClick5={this.advancedss}
                        workShopList={workShopList}
                        advanced={advanced}
                    ></TopForm>
                </BasicLayoutSearch>
                <Alert
                    message={<div>已选择 <span style={{ color: '#5abcff' }}>{selectedRowKeys.length}</span> 项，包括 <span style={{ color: '#5abcff' }}>{batchNoStr11.length}</span> 个批号<span>{batchNoStr}</span> <a onClick={() => this.setState({ selectedRowKeys: [], selectedRows: [] })}>
                        清除
                    </a></div>}
                    type="info"
                    showIcon
                    style={{ width: '99%', margin: 'auto' }}
                />
                <BasicLayout
                    name='欠料管理'
                    icon="table"
                    buttons={[
                        <RefreshButton key={1} onClick={() => this.refresh()} icon='sync' />,
                        <PrintButton key={2} onClick={() => this.print()} icon='printer' />,
                        <TJButton key={3} onClick={() => this.putIn()} />,
                        <BJButton key={4} onClick={() => this.redact()} />,
                        <CHFButton key={5} onClick={() => this.urge()} />,
                        
                        // <Button type='primary' key={0} onClick={() => this.refresh()}>刷新</Button>,
                        // <Button type='primary' key={1} onClick={() => this.print()}>打印</Button>,
                        // <Button type='primary' key={2} onClick={() => this.putIn()}>提交欠料</Button>,
                        // <Button type='primary' key={3} onClick={() => this.redact()}>编辑交期</Button>,
                        // <Button type='primary' key={4} onClick={() => this.urge()}>催回复</Button>,
                    ]}
                >
                    <TableCustomize
                        rowSelection={rowSelection}
                        columns={columns}
                        rowKey={(record) => record.id}
                        dataSource={dataSource}
                        pagination={false}
                        loading={loading}
                        allowDrafting={true}
                        allowEditable={this.loadData}
                        expandRowByClick={true}
                        expandedRowRender={expandedRowRender}
                        expandedRowKeys={this.state.row}
                        onExpand={(expanded, record) => this.onExpand(expanded, record)}
                        rowClassName={(record, index) => {
                            return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
                        }}
                    // onRow={(record, index) => ({
                    //     onClick: this.onExpand.bind(this, true, record)
                    // })}
                    >
                    </TableCustomize>
                    <BasicPagination pageNum={paging.pageNum} pageSize={paging.pageSize} total={paging.total} loadData={this.fetch} />
                </BasicLayout>
                <Modal
                    visible={visible}
                    destroyOnClose
                    title={'编辑交期'}
                    onOk={this.submitMenu}
                    onCancel={this.handleCancel}
                    okText="保存"
                    cancelText="取消"
                    confirmLoading={confirmLoading}
                >
                    <AddForm
                        ref={node => (this.formAdd = node)}
                        formData={formData}
                    />
                </Modal>
            </div>
        )
    }
}
